package com.example.r2022913.controller.WxController;


import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.r2022913.common.ApiRestResponse;
import com.example.r2022913.exception.ExceptionEnum;
import com.example.r2022913.model.entity.WxEntity.CodeEntity;
import com.example.r2022913.model.entity.WxEntity.WXUser;
import com.example.r2022913.service.WxService.WXUserService;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.RequestBody;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("wx/user")
@Api(tags = "wx小程序服务  UserController")
@CrossOrigin
@Slf4j
public class WXUserController {

    @Autowired
    WXUserService wxuserService;

    //TODO 解决调用获取手机号接口报错的问题

    //和微信小程序绑定的appid
    @Value("${appid}")
    private String appid;

    //和微信小程序绑定的secret
    @Value("${secret}")
    private String secret;

    public Map getOpenidAndSessionKey(String appid, String secret, String code) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();

        log.info("appid是==》{}", appid);
        log.info("secret-->{}", secret);
        log.info("从前端拿到的code是===>{}", code);


        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        Request request = new Request.Builder().url(url).build();

        Response response = okHttpClient.newCall(request).execute();

        if (response.isSuccessful()) {
            JSONObject jsonResult = JSONObject.parseObject(response.body().string());

            log.info("获取的响应结果体是===》{}", jsonResult);

            String openid = jsonResult.getString("openid");
            String sessionKey = jsonResult.getString("session_key");

            System.out.println("openid:   " + openid);
            System.out.println("sessionKey:   " + sessionKey);
            HashMap<Object, Object> hashmap = new HashMap<>();
            hashmap.put("openid", openid);
            hashmap.put("sessionKey", sessionKey);
            return hashmap;
        }

        return null;

    }

    @ApiOperation("根据前端发来的code获取微信open_id 和 session_key 以后使用其做权限验证")
    @PostMapping("/onLogin")
    @ResponseBody
    public ApiRestResponse wxLogin(@org.springframework.web.bind.annotation.RequestBody JSONObject json
    ) throws IOException {

        //1 调用自定义函数拿到oppenid 和 sessionkey
        Map res = getOpenidAndSessionKey(appid, secret, json.get("code").toString());

        //如果为空报错
        if (MapUtil.isEmpty(res)) {
            return ApiRestResponse.error(ExceptionEnum.WX_LOGIN_ERROR);
        }

        //2 添加用户信息到表中
        //拿到openid 和  sessionkey
        String openid = res.get("openid").toString();
        String sessionKey = res.get("sessionKey").toString();

        log.info("调用自定义函数获取的oppenid===》{}", openid);
        log.info("调用自定义函数获取的sessionKey===》{}", sessionKey);

        //获取微信小程序getUserProfile接口前端传来的数据
        System.out.println("rawData:   " + json.get("rowData") + "");

        //获取这个用户
        WXUser user = wxuserService.getOne(new QueryWrapper<WXUser>().eq("open_id", openid));

        // uuid生成唯一key，用于维护微信小程序用户与服务端的会话
        String skey = UUID.randomUUID().toString();

        //获取不到为新用户 准备进行添加
        if (user == null) {
            Map rawDataJson = (Map) json.get("rowData");

            // 用户信息入库
            String nickName = rawDataJson.get("nickName") + "";
            String avatarUrl = rawDataJson.get("avatarUrl") + "";
//            String gender = rawDataJson.getString("gender");
//            String city = rawDataJson.getString("city");
//            String country = rawDataJson.getString("country");
//            String province = rawDataJson.getString("province");

            user = new WXUser();
            user.setOpenId(openid);
            user.setCreateTime(new Date());
            user.setSessionKey(sessionKey);
            user.setSkey(skey);
//            user.setCity(city);
//            user.setProvince(province);
//            user.setCountry(country);
            user.setAvatarUrl(avatarUrl);
//            user.setGender(Integer.parseInt(gender));
            user.setNickname(nickName);

            wxuserService.save(user);
        } else {
            // 已存在，更新用户登录时间
            // 重新设置会话skey
            user.setSkey(skey);
            wxuserService.updateById(user);
        }

        //返回授权uuid
        WXUser userBySkey = wxuserService.getOne(new QueryWrapper<WXUser>().eq("skey", skey));

        Map<String, Object> map = new HashMap<>();
        map.put("skey", skey);
        map.put("userId", userBySkey.getId());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("avatarUrl",userBySkey.getAvatarUrl());
        jsonObject.put("nickName",userBySkey.getNickname());

        map.put("userinfoback",jsonObject);

//        map.put("AvatarUrl",userBySkey.getAvatarUrl());
//        map.put("nickname",userBySkey.getNickname());
        return ApiRestResponse.success(map);
    }


//
//        if (response.isSuccessful()) {
//            JSONObject jsonResult = JSONObject.parseObject(response.body().string());
//
//            log.info("获取的响应结果体是===》{}", jsonResult);
//
//            String openid = jsonResult.getString("openid");
//            String sessionKey = jsonResult.getString("session_key");
//
//            System.out.println("openid:   " + openid);
//            System.out.println("sessionKey:   " + sessionKey);
//            //获取微信小程序getUserProfile接口前端传来的数据
//            System.out.println("rawData:   " + json.get("rowData") + "");
//
//            //TODO 把接受来的用户数据添加到用户表中 并且在前端存储到本地
//            //            User user = userService.getOne(new QueryWrapper<User>().eq("open_id", openid));
//            // uuid生成唯一key，用于维护微信小程序用户与服务端的会话
//            String skey = UUID.randomUUID().toString();
//            if (user == null) {
//                Map rawDataJson = (Map) json.get("rowData");
//
//                // 用户信息入库
//                String nickName = rawDataJson.get("nickName") + "";
//                String avatarUrl = rawDataJson.get("avatarUrl") + "";
////            String gender = rawDataJson.getString("gender");
////            String city = rawDataJson.getString("city");
////            String country = rawDataJson.getString("country");
////            String province = rawDataJson.getString("province");
//
//                user = new User();
//                user.setOpenId(openid);
//                user.setSkey(skey);
//                user.setCreateTime(new Date());
////            user.setLastVisitTime(new Date());
//                user.setSessionKey(sessionKey);
////            user.setCity(city);
////            user.setProvince(province);
////            user.setCountry(country);
//                user.setAvatarUrl(avatarUrl);
////            user.setGender(Integer.parseInt(gender));
//                user.setNickname(nickName);
//
//                userService.save(user);
//            } else {
//                // 已存在，更新用户登录时间
//                // 重新设置会话skey
//                user.setSkey(skey);
//                userService.updateById(user);
//            }
//
//            //返回授权uuid
//            User skey1 = userService.getOne(new QueryWrapper<User>().eq("skey", skey));
//
//            Map<String, Object> map = new HashMap<>();
//            map.put("skey", skey);
//            map.put("userId", skey1.getId());
//            return ApiRestResponse.success(map);
//        }

    //return ApiRestResponse.error(SkyExceptionEnum.NEED_LOGIN);

//            CREATE TABLE `sys_adminmail_usermail` (
//  `admin_id` bigint(30) NOT NULL AUTO_INCREMENT COMMENT '信箱id',
//  `user_code` varchar(50) COLLATE utf8mb4_bin NOT NULL COMMENT '用户code',
//  `type_name` varchar(20) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '意见类型名称',
//  `department_name` varchar(20) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '部门名称',
//  `contact_name` varchar(30) COLLATE utf8mb4_bin DEFAULT '' COMMENT '联系人',
//  `contact_number` varchar(30) COLLATE utf8mb4_bin DEFAULT '' COMMENT '联系人电话',
//  `user_title` varchar(30) COLLATE utf8mb4_bin DEFAULT '' COMMENT '用户信件标题',
//  `user_content` varchar(1024) COLLATE utf8mb4_bin DEFAULT '' COMMENT '用户信件内容',
//  `user_send_time` datetime DEFAULT NULL COMMENT '用户发送时间',
//  `admin_content` varchar(1024) COLLATE utf8mb4_bin DEFAULT '' COMMENT '管理员信件内容',
//  `admin_send_time` datetime DEFAULT NULL COMMENT '管理员发送时间',
//  `visible` char(1) COLLATE utf8mb4_bin DEFAULT '0' COMMENT '是否回复（1已回复，0未回复）',
//                    PRIMARY KEY (`admin_id`) USING BTREE
//) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='管理员信箱';


//            User user = userService.getOne(new QueryWrapper<User>().eq("open_id", openid));
//            // uuid生成唯一key，用于维护微信小程序用户与服务端的会话
//            String skey = UUID.randomUUID().toString();
//            if (user == null) {
//                Map rawDataJson =(Map) json.get("rowData");
//
//                // 用户信息入库
//                String nickName = rawDataJson.get("nickName")+"";
//                String avatarUrl = rawDataJson.get("avatarUrl")+"";
////            String gender = rawDataJson.getString("gender");
////            String city = rawDataJson.getString("city");
////            String country = rawDataJson.getString("country");
////            String province = rawDataJson.getString("province");
//
//                user = new User();
//                user.setOpenId(openid);
//                user.setSkey(skey);
//                user.setCreateTime(new Date());
////            user.setLastVisitTime(new Date());
//                user.setSessionKey(sessionKey);
////            user.setCity(city);
////            user.setProvince(province);
////            user.setCountry(country);
//                user.setAvatarUrl(avatarUrl);
////            user.setGender(Integer.parseInt(gender));
//                user.setNickname(nickName);
//
//                userService.save(user);
//            } else {
//                // 已存在，更新用户登录时间
//                // 重新设置会话skey
//                user.setSkey(skey);
//                userService.updateById(user);
//            }
//
//            //返回授权uuid
//            User skey1 = userService.getOne(new QueryWrapper<User>().eq("skey", skey));
//
//            Map<String, Object> map = new HashMap<>();
//            map.put("skey",skey);
//            map.put("userId",skey1.getId());
//            return ApiRestResponse.success(map);
//        }
//
//        return ApiRestResponse.error(SkyExceptionEnum.NEED_LOGIN);


    @GetMapping("/userinfo")
    @ApiOperation(value = "调用微信服务器接口获取用户信息")
    public ApiRestResponse get_userinfo(@RequestParam String code) throws IOException {
        log.info("获取的code是===》{}", code);

        log.info("appid 是==》{}", appid);
        log.info("secret -->{}", secret);

        //使用OKhttpclient
        OkHttpClient okHttpClient = new OkHttpClient();

        //封装Url
        String url = "https://api.weixin.qq.com/cgi-bin/token?appid=" + appid + "&secret=" + secret + "&grant_type=client_credential";

        //创建请求 import okhttp3.Request;
        Request request = new Request.Builder().url(url).build();


        //获取请求响应  import okhttp3.Response;
        Response response = okHttpClient.newCall(request).execute();

        log.info("发起请求后的响应是===》{}", response);

        //创建一个hashmap  存用户数据
        Map<String, String> userinfoMap = new HashMap<>();

        //成功
        if (response.isSuccessful()) {

            //使用fastjson把response的字符串转化为json对象
            //方便后续使用
            JSONObject jsonResult = JSONObject.parseObject(response.body().string());

            log.info("获取的响应结果体是===》{}", jsonResult);

            //得到access_token
            String access_token = jsonResult.getString("access_token");
            log.info("获取到的access_token是===>{}", access_token);

            getUserPhone(access_token, code);


            return ApiRestResponse.success();
        } else {
            return ApiRestResponse.error(405, "失败获取access_token");
        }

    }


    String getUserPhone(String access_token, String code) throws IOException {
        log.info("进入到了获取手机号方法");
        log.info("获取的code是===》{}", code);

        //使用OKhttpclient
        OkHttpClient okHttpClient = new OkHttpClient();


        //https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN

        //封装Url
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
        log.info("获取电话号请求封装的url是===》{}", url);

        //构建请求体
//        RequestBody formBody = new FormBody.Builder()
//                .add("code",code)
//                .build();
        CodeEntity codeEntity = new CodeEntity();
        codeEntity.setCode(code);
        String s = JSONObject.toJSONString(codeEntity);

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), s);
//        MediaType.parse("application/json; charset=utf-8"), json
//        RequestBody body = RequestBody.create(JSON,s);


        //创建请求 import okhttp3.Request;
        Request request = new Request.Builder().url(url).post(body).build();

        //获取请求响应  import okhttp3.Response;
        Response response = okHttpClient.newCall(request).execute();

        //成功
        if (response.isSuccessful()) {

            //使用fastjson把response的字符串转化为json对象
            //方便后续使用
            JSONObject jsonResult = JSONObject.parseObject(response.body().string());

            log.info("获取的响应结果体是===》{}", jsonResult);


            //return ApiRestResponse.success();
        }

        return null;
    }
}
